/**
 * $version:  0.1 
 * $Date: 2011-01-21 
 *
 * Copyright (C) 2010-2011 Jinrui Software. All rights reserved.
 *
 */
package org.jawa.util;

import java.io.InputStream;
import java.net.URL;

/**
 * 实用工具类，用以协助加载类或资源,例如:
 * 
 * <pre>
 * Class.forName(className);
 * </pre>
 * 
 * @author Y-N
 */
public class ClassUtils {

	private static ClassUtils instance = new ClassUtils();

	/**
	 * 加载具有指定名称的类。
	 * 
	 * @param className
	 *            类名
	 * @return the <code>Class</code> 对象
	 * @throws ClassNotFoundException
	 *             没有找到
	 */
	public static Class forName(String className) throws ClassNotFoundException {
		return instance.loadClass(className);
	}

	/**
	 * 以流的方式加载资源。
	 * 
	 * @param name
	 *            该资源在classpath中存在的名称
	 * @return the 资源流,如果没有找到返回 <tt>null</tt>
	 */
	public static InputStream getResourceAsStream(String name) {
		return instance.loadResource(name);
	}

	private Class loadClass(String className) throws ClassNotFoundException {
		Class theClass = null;
		try {
			theClass = Class.forName(className);
		} catch (ClassNotFoundException e1) {
			try {
				theClass = Thread.currentThread().getContextClassLoader()
						.loadClass(className);
			} catch (ClassNotFoundException e2) {
				theClass = getClass().getClassLoader().loadClass(className);
			}
		}
		return theClass;
	}

	private InputStream loadResource(String name) {
		InputStream in = getClass().getResourceAsStream(name);
		if (in == null) {
			in = Thread.currentThread().getContextClassLoader()
					.getResourceAsStream(name);
			if (in == null) {
				in = getClass().getClassLoader().getResourceAsStream(name);
			}
		}
		return in;
	}

	/**
	 * 构造函数
	 */
	private ClassUtils() {
		// 不可实例化
	}
}
